import React, { Component, Fragment } from 'react';
import { Form, Input, Select, DatePicker, Button, Modal, Badge } from 'antd';
import { connect } from 'dva';
import Media from 'react-media';
import SelectForm from '@/components/SelectForm';
import ManageList from '@/components/ManageList';
import TableButtons from '@/components/TableButtons';
import RightDraw from '@/components/RightDraw';
import StandardTable from '@/components/StandardTable';
import UpkeepDetail from './UpkeepDetail';
import moment from 'moment';
import router from 'umi/router';
import FileImport from '@/components/FileImport';
import AdSelect from '@/components/AdSelect';
import { billStateList, billStateOnlyReadList } from '@/utils/constans';
import { vitifyCheck, formateDateToMin } from '@/utils/common';
import AntdFormItem from '@/components/AntdFormItem';
import SearchSelect from '@/components/SearchSelect';
import { columns1, columnsBillNo } from '@/pages/Common/common';
import AdSearch from '@/components/AdSearch';
import FileReader from '@/components/FileReader';
import AdButton from '@/components/AdButton';
import { codes, PayMethod } from './utils';
const { RangePicker, MonthPicker } = DatePicker;
const dateFormat = 'YYYY-MM-DD';
const FormItem = Form.Item;
const { Option } = Select;
const confirm = Modal.confirm;
//const { MonthPicker } = DatePicker;

@ManageList
@connect(({ upkeep, component, loading, common }) => ({
    upkeep,
    loading: loading.effects['upkeep/upkeepList'],
    ownCompany: common.ownCompany,
    searchValue: component.searchValue,
    dictObject: common.dictObject,
}))
@Form.create()
export default class UpkeepList extends Component {
    state = {
        visible: false,
        id: '',
        name: '',
        formValues: {},
        cars: [],
        cars2: [],
        billNos: [],
        expandForm: false,
        selectedRows: [],
        isBillStatus: '',
        visibleFile: false,
    };
    className = 'UpkeepList';
    columns = [
        {
            title: '单据号',
            dataIndex: 'upkeepNo',
            render: (text, record) => (
                <AdButton
                    mode="a"
                    onClick={e => this.showDetail(e, record.id, text, record)}
                    text={text}
                    code={codes.showDetail}
                />
            ),
            fixed: this.props.isMobile ? false : true,
        },
        {
            title: '状态',
            dataIndex: 'billStatus',
            render: (text, record) => (
                <AdSelect
                    onlyRead={true}
                    value={text ? text : record.status}
                    data={billStateOnlyReadList}
                />
            ),
            width: 100,
        },
        {
            title: '主车牌',
            dataIndex: 'cartPlateNo',
        },
        {
            title: '挂车牌',
            dataIndex: 'trailerPlateNo',
        },
        {
            title: '所属公司',
            dataIndex: 'ownCompanyName',
            render: text => <span title={text}>{text}</span>,
            width: 250,
        },
        {
            title: '结算周期',
            dataIndex: 'settlementDate',
        },
        {
            title: '里程数',
            dataIndex: 'currentMileage',
        },
        {
            title: '附件',
            dataIndex: 'attaQuantity',
            width: 80,
            render: (text, record) =>
                text &&
                Number(text) > 0 && (
                    <Badge className="cus_badge" count={text}>
                        <div className="head-example">
                            <FileReader
                                type="list"
                                count={text}
                                urlType="tms"
                                params={{ bizId: record.id, fileBizType: 'UPKEEP_MANA' }}
                            />
                        </div>
                    </Badge>
                ),
        },
        {
            title: '应付币种',
            dataIndex: 'currencyType',
            render: text => (
                <AdSelect onlyRead={true} value={text} data={this.props.dictObject['currency-type']} />
            ),
            width: 100,
        },
        {
            title: '应付金额',
            dataIndex: 'totalFee',
            render: text => {
                return <span>{text && Number(text) !== 0 ? Number(text).toFixed(2) : 0}</span>;
            },
        },
        {
            title: '实付币种',
            dataIndex: 'realCurrencyType',
            render: text => (
                <AdSelect onlyRead={true} value={text} data={this.props.dictObject['currency-type']} />
            ),
            width: 100,
        },
        {
            title: '实付金额',
            dataIndex: 'realPayFee',
            render: text => {
                return <span>{text && Number(text) !== 0 ? Number(text).toFixed(2) : 0}</span>;
            },
        },
        {
            title: '类型',
            dataIndex: 'upkeepType',
            render: text => (
                <AdSelect onlyRead={true} value={text} data={this.props.dictObject['upkeep-type']} />
            ),
        },
        {
            title: '支付方式',
            dataIndex: 'payMethod',
            render: (text, record) => <AdSelect onlyRead={true} value={text} data={PayMethod} />,
        },
        {
            title: '保养厂/维修厂',
            dataIndex: 'upkeepFactory',
        },
        {
            title: '保养日期/维修日期',
            dataIndex: 'upkeepTime',
        },
        {
            title: '送保人/送修人',
            dataIndex: 'upkeepPerson',
        },
        {
            title: '账单号',
            dataIndex: 'billNo',
        },
        {
            title: '创建人',
            dataIndex: 'createBy',
            render: text => (
                <AdSearch
                    label="loginName"
                    name="sysName"
                    value={this.props.searchValue[text]}
                    onlyRead={true}
                />
            ),
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
        },
        {
            title: '更新人',
            dataIndex: 'updateBy',
            render: text => (
                <AdSearch
                    label="loginName"
                    name="sysName"
                    value={this.props.searchValue[text]}
                    onlyRead={true}
                />
            ),
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            render: text => <span>{text ? moment(text).format(formateDateToMin) : ''}</span>,
        },
    ];

    componentDidMount() {
        this.dispatchFun('upkeep/upkeepList', {});

        // 查询字典：保养类型
        this.props.dispatch({
            type: 'common/querytDictByCode',
            payload: { code: 'upkeep-type' },
        });
        //币种：
        this.props.dispatch({
            type: 'common/querytDictByCode',
            payload: { code: 'currency-type' },
        });
    }

    toggleForm = expandForm => {
        this.setState({
            expandForm,
        });
    };

    // 分页操作
    handleStandardTableChange = param => {
        const { formValues } = this.state;
        const params = {
            ...formValues,
            ...param,
        };
        this.dispatchFun('upkeep/upkeepList', params);
    };

    // 重置条件查询表单
    handleFormReset = () => {
        this.setState({ formValues: {}, cars: [], billNos: [] });
        this.dispatchFun('upkeep/upkeepList', {});
    };

    // 执行条件查询表单
    handleSearch = values => {
        // if (!values) {
        //   return;
        // }
        const { upkeepTime, ...value } = values;
        if (upkeepTime && upkeepTime.length > 0) {
            value.upkeepStartTime = moment(upkeepTime[0]).format(dateFormat);
            value.upkeepEndTime = moment(upkeepTime[1]).format(dateFormat);
        }
        const { cars, billNos, cars2 } = this.state;
        if (cars.length > 0) {
            const vehicleId = cars.map(v => {
                return v.id;
            });
            value.vehicleId = vehicleId.join(',');
        } else {
            value.vehicleId = '';
        }

        if (cars2.length > 0) {
            const vehicleId = cars.map(v => {
                return v.id;
            });
            value.trailerVehicleId = vehicleId.join(',');
        } else {
            value.trailerVehicleId = '';
        }

        if (billNos.length > 0) {
            const billId = billNos.map(v => {
                return v.id;
            });
            value.billId = billId.join(',');
        } else {
            value.billId = '';
        }
        this.setState({
            formValues: value,
        });
        this.dispatchFun('upkeep/upkeepList', value);
    };

    // 跳转 新增页面
    handleAdd = () => {
        const { dispatch } = this.props;
        router.push('/carDaily/upkeepList/addupkeep');
    };

    // 跳转 编辑页面
    handleEdit = () => {
        const { dispatch } = this.props;
        const { id, name } = this.state;
        router.push(`/carDaily/upkeepList/editupkeep/${id}`);
        this.closeDetail();
    };

    // 关闭右抽屉
    closeDetail = () => {
        this.setState({
            visible: false,
        });
    };
    // 打开右抽屉
    showDetail = (e, id, name, record) => {
        e.stopPropagation();
        const status = record.billStatus ? record.billStatus : record.status;
        const isBillStatus = status === 'CONFIRM' || status === 'WAIT';
        this.setState({
            visible: true,
            id,
            name,
            isBillStatus,
        });
        this.dispatchFun('upkeep/upkeepDetail', { id });
    };

    // dispatch 方法
    dispatchFun(type, params) {
        const { dispatch, searchValue } = this.props;

        dispatch({
            type: type,
            payload: params,
            callback: data => {
                let valueList = [];
                data.map(v => {
                    if (type === 'upkeep/upkeepList' && data) {
                        const labels = ['updateBy', 'createBy'];
                        labels.map(item => {
                            if (v[item] && !valueList.includes(v[item])) {
                                valueList.push(v[item]);
                                !searchValue[v[item]] &&
                                    dispatch({
                                        type: 'component/querySearchValue',
                                        payload: { params: { loginName: v[item] }, url: 'tms/tms-upkeep/selectUser_s' },
                                    });
                            }
                        });
                    }
                });
            },
        });
    }
    getValue = (values, type) => {
        this.setState({
            [type]: values,
        });
    };
    handleSelectRows = selectedRows => {
        this.setState({
            selectedRows,
        });
    };

    /**
     * 生成账单
     */
    generatedBills = () => {
        const { dispatch } = this.props;
        const { selectedRows, formValues } = this.state;
        const checkBill = this.checkBill();
        if (!checkBill) return;
        dispatch({
            type: 'upkeep/generatedBills',
            payload: { ids: selectedRows.map(v => v.id) },
            callback: data => {
                if (!data) return;
                this.setState({
                    selectedRows: [],
                });
                this.dispatchFun('upkeep/upkeepList', formValues);
                //跳转到账单的编辑页面
                router.push(`/carAccount/billList/editBill/${data}`);
            },
        });
    };

    /**
     * 生成账单校验 状态已提交，同一公司，同一加油方式
     */

    checkBill = () => {
        const { selectedRows } = this.state;
        const ownCompanyName = vitifyCheck({
            selectedRows,
            key: 'ownCompanyName',
            warn: '所选记录必须所属公司相同！',
        });
        if (!ownCompanyName) return false;
        const payMethod = vitifyCheck({
            selectedRows,
            key: 'payMethod',
            warn: '支付方式不同，不能合并生成帐单！',
        });
        if (!payMethod) return false;
        return true;
    };

    //删除
    removeRecord = () => {
        const { dispatch } = this.props;
        const { id, visible, formValues } = this.state;
        confirm({
            title: '确定要删除这条数据吗？',
            content: ' ',
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: () => {
                dispatch({
                    type: 'upkeep/deleteUpkeep',
                    payload: { id: id },
                    callback: () => {
                        this.setState({ visible: false, selectedRows: [] });
                        this.dispatchFun('upkeep/upkeepList', formValues);
                    },
                });
            },
        });
    };

    //导入
    handleImportFile = () => {
        const { visibleFile } = this.state;
        this.setState({ visibleFile: !visibleFile });
    };
    getSelectList = () => {
        const { dispatch, searchValue } = this.props;
        const { formValues } = this.state;
        dispatch({
            type: 'upkeep/upkeepList',
            payload: formValues,
            callback: data => {
                let valueList = [];
                data.map(v => {
                    const labels = ['updateBy', 'createBy'];
                    labels.map(item => {
                        if (v[item] && !valueList.includes(v[item])) {
                            valueList.push(v[item]);
                            !searchValue[v[item]] &&
                                dispatch({
                                    type: 'component/querySearchValue',
                                    payload: { params: { loginName: v[item] }, url: 'tms/tms-upkeep/selectUser_s' },
                                });
                        }
                    });
                });
            },
        });
    };

    selectAll = () => {
        const { dispatch } = this.props;
        const { formValues } = this.state;
        dispatch({
            type: 'upkeep/selectAll',
            payload: formValues,
            callback: data => {
                this.setState({
                    selectedRows: [],
                });
                if (!data) return;

                this.dispatchFun('upkeep/upkeepList', formValues);
                //跳转到账单的编辑页面
                router.push(`/carAccount/billList/editBill/${data}`);
            },
        });
    };
    render() {
        const {
            form,
            loading,
            ownCompany,
            upkeep: { upkeepList, detail },
            isMobile,
            dictObject,
        } = this.props;
        const {
            id,
            visible,
            expandForm,
            visibleFile,
            isBillStatus,
            selectedRows,
            formValues,
        } = this.state;
        const { getFieldDecorator } = form;
        const commonParams = {
            getFieldDecorator,
        };
        // firstForm 参数
        const firstFormItem = (
            <FormItem label="单据号">
                {getFieldDecorator('upkeepNo')(<Input placeholder="请输入" />)}
            </FormItem>
        );
        const secondFormItem = (
            <AntdFormItem label="状态" code="billStatus" {...commonParams}>
                <AdSelect data={billStateList} isExist={true} mode="multiple" />
            </AntdFormItem>
        );
        // const lastFormItem = (
        //   <FormItem label="结算周期" code="settlementDate" {...commonParams}>
        //      <MonthPicker style={{ width: "100%" }} />
        //   </FormItem>
        // );

        // secondForm 参数
        const otherFormItem = [
            [
                <FormItem label="保养时间">
                    {getFieldDecorator('upkeepTime')(<RangePicker style={{ width: '100%' }} />)}
                </FormItem>,
            ],
            [
                <FormItem label="车牌号">
                    {getFieldDecorator('vehicleId')(
                        <SearchSelect
                            dataUrl="tms/tms-upkeep/selectVehicle"
                            url="tms/tms-upkeep/selectVehicleView_s" // selectedData只只有id时需要传url
                            selectedData={this.state.cars} // 选中值
                            multiple={false} // 是否多选
                            showValue="cartPlateOneNo"
                            searchName="cartPlate"
                            columns={columns1} // 表格展示列
                            onChange={values => this.getValue(values, 'cars')} // 获取选中值
                            scrollX={480}
                            id="upkeep_1"
                            allowClear={true}
                        />
                    )}
                </FormItem>,
                <FormItem label="所属公司">
                    {getFieldDecorator('mdsCompanyId')(
                        <Select
                            showSearch
                            allowClear={true}
                            filterOption={(input, option) =>
                                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                            }
                            placeholder="请选择"
                            style={{ width: '100%' }}
                        >
                            <Option value="">请选择</Option>
                            {ownCompany.map((v, i) => {
                                return (
                                    <Option key={i} value={v.customerCode}>
                                        {v.customerName}
                                    </Option>
                                );
                            })}
                        </Select>
                    )}
                </FormItem>,
                <FormItem label="保养类型">
                    {getFieldDecorator('upkeepTypeCode')(
                        <Select placeholder="请选择" allowClear={true}>
                            <Option value="">请选择</Option>
                            {dictObject['upkeep-type'] &&
                                dictObject['upkeep-type'].map(item => (
                                    <Option key={item.code}>{item.value}</Option>
                                ))}
                        </Select>
                    )}
                </FormItem>,
            ],
            [
                <FormItem label="挂车车牌号">
                    {getFieldDecorator('trailerVehicleId')(
                        <SearchSelect
                            dataUrl="tms/tms-upkeep/selectVehicle"
                            url="tms/tms-upkeep/selectVehicleView_s" // selectedData只只有id时需要传url
                            selectedData={this.state.cars2} // 选中值
                            multiple={false} // 是否多选
                            showValue="cartPlateOneNo"
                            searchName="cartPlate"
                            columns={columns1} // 表格展示列
                            onChange={values => this.getValue(values, 'cars2')} // 获取选中值
                            scrollX={480}
                            id="upkeep_1"
                            allowClear={true}
                        />
                    )}
                </FormItem>,
                <FormItem label="账单号">
                    {getFieldDecorator('billId')(
                        <SearchSelect
                            dataUrl="tms/tms-upkeep/selectTmsBillList_s"
                            selectedData={this.state.billNos} // 选中值
                            multiple={false} // 是否多选
                            showValue="billNo"
                            searchName="billNo"
                            columns={columnsBillNo} // 表格展示列
                            onChange={values => this.getValue(values, 'billNos')} // 获取选中值
                            scrollX={200}
                            id="upkeep_2"
                            allowClear={true}
                            payload={{ type: 'UPKEEP' }}
                        />
                    )}
                </FormItem>,
                <FormItem label="支付方式">
                    {getFieldDecorator('payMethod')(
                        <Select placeholder="请选择" allowClear={true}>
                            <Option value="">请选择</Option>
                            {PayMethod.map(item => (
                                <Option key={item.code}>{item.value}</Option>
                            ))}
                        </Select>
                    )}
                </FormItem>,
            ],
            [
                <FormItem label="结算周期">
                    {getFieldDecorator('settlementDate')(

                        <MonthPicker style={{ width: "100%" }} />

                    )}
                </FormItem>,

                'operatorButtons'
            ]
            // ['operatorButtons'],
        ];

        const selectFormParams = {
            firstFormItem,
            secondFormItem,
            otherFormItem,
            // lastFormItem,
            form,
            code: codes.select,
            className: this.className,
            toggleForm: this.toggleForm,
            handleFormReset: this.handleFormReset,
            handleSearch: this.handleSearch,
        };

        const tableButtonsParams = {
            show: false,
            code: codes.add,
            handleAdd: this.handleAdd,
            selectedLength: selectedRows.length,
            pagination: upkeepList.pagination,
            selectAll: this.selectAll,
            code: codes.bill,
            buttons: (
                <Button.Group>
                    <AdButton onClick={() => this.handleImportFile()} text="导入" code={codes.import} />
                    <AdButton
                        disabled={!selectedRows.length > 0}
                        onClick={() => this.generatedBills()}
                        text={`生成账单${selectedRows.length > 0 ? '(' + selectedRows.length + ')' : ''}`}
                        code={codes.bill}
                    />
                </Button.Group>
            ),
        };

        const rightDrawParams = {
            isMobile,
            visible,
            code: codes.showDetail,
            title: '维修保养详情',
            closeDetail: this.closeDetail,
            buttons: (
                <span>
                    <AdButton
                        onClick={() => this.removeRecord(1)}
                        text="删除"
                        type="danger"
                        ghost
                        code={codes.remove}
                    />
                    <AdButton
                        disabled={!isBillStatus}
                        text="编辑"
                        type="primary"
                        style={{ marginLeft: 8 }}
                        onClick={this.handleEdit}
                        code={codes.edit}
                    />
                </span>
            ),
        };
        const billStatus = formValues.billStatus;
        const disabledRowSelected =
            billStatus && billStatus.length === 1 && billStatus.includes('CONFIRM') ? false : true;
        return (
            <Fragment>
                <FileImport
                    visibleFile={visibleFile}
                    handleCancel={() => {
                        this.handleImportFile();
                    }}
                    urlImport={`tms/tms-upkeep-detail/importUpkeep`}
                    urlCase={`attachment/维修保养导入模板.xlsx`}
                    queryData={[this.getSelectList]}
                    accept=".xls,.xlsx"
                />
                <SelectForm {...selectFormParams} />
                <TableButtons {...tableButtonsParams} />
                <StandardTable
                    getCheckboxProps={record => {
                        const status = record.billStatus ? record.billStatus : record.status;
                        const checked = status === 'CONFIRM' || status === 'WAIT';
                        return !checked;
                    }}
                    loading={loading}
                    selectedRows={selectedRows}
                    data={upkeepList}
                    onSelectRow={this.handleSelectRows}
                    columns={this.columns}
                    disabledSelectedRows={{ code: ['billStatus', 'status'], value: ['CONFIRM', 'WAIT'] }}
                    className={this.className}
                    expandForm={expandForm}
                    onPaginationChange={this.handleStandardTableChange}
                    code={codes.page}
                />
                <RightDraw {...rightDrawParams}>
                    {/* 维修保养详情 */}
                    <UpkeepDetail isMobile={isMobile} id={id} />
                </RightDraw>
            </Fragment>
        );
    }
}
